<template>
  <div class="excel">
    <div v-loading="loading"
         element-loading-text="文档自动生成中，请稍等片刻"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">
      <el-alert
          title="只允许上传.doc和.docx文件, 最大只能上传100Mb的文件, 如果上传成功会显示已上传的文件"
          type="warning"
          center
          show-icon>
      </el-alert>
      <el-upload
          class="upload-demo"
          :limit="1"
          drag
          accept=".doc,.docx"
          :on-exceed="handleExceed"
          :on-error="error"
          :on-success="success"
          :on-progress="progress"
          :before-upload="uploadBefore"
          :before-remove="beforeRemove"
          action="http://localhost:8881/uploadFile"
          id="upload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Word文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div id="progress">
        <el-progress :text-inside="true" :stroke-width="20" :percentage=percentage></el-progress>
      </div>
    </div>
  </div>
</template>

<script>
  import {generateFile} from "../../network/file"
  export default {
    name: "excel",
    data(){
      return {
        percentage: 0,
        loading: false
      }
    },
    methods:{
      handleExceed(files, fileList) {
        this.$message.error(`只能上传1个文件，如果要重新上传文件请先删除已上传的文件`);
      },
      error(){
        this.$message.error('上传失败，请打开后台服务')
        this.percentage=0
      },
      uploadBefore(file){
        const strRegex = "(.doc|.docx)$";
        const re= new RegExp(strRegex);
        if(re.test(file.name)){
          return true
        }else{
          this.$message.error(`${file.name}格式不对，请上传.doc和.docx文件`)
          return false
        }
      },
      beforeRemove(file, fileList) {
        this.percentage=0
      },
      progress(event, file, fileList){
        this.percentage=event.percent
      },
      async success(){
        this.loading=true
        const res=await generateFile()
        if(res.status===200){
          for(let i=1000000000;i>0;i--){}
          window.location.href = 'http://localhost:8881/word/updateWord'
          this.loading=false
          this.$message.success("文件生成成功！")
          this.$store.commit("setExcel",0)
          this.$store.commit("setNext",0)
          this.$router.push("/")
        }
      }
    }
  }
</script>

<style scoped>
  .excel{
    font-weight: bold;
  }
  #upload{
    width: 24%;
    padding-left: 38%;
    margin-top: 3rem;
    margin-bottom: 1rem;
  }
  #progress{
    margin-left: 38%;
    width: 24%;
  }
  #file-progress{
    margin-top: 2rem;
    margin-left: 45.5%;
  }
</style>